import { CMEVENTS } from '@amcax/base';
import { userEvents } from '@app-cad/module';
import React, { useEffect, useRef, useState } from 'react';

interface ErrorItem {
  time: string;
  code: number;
  message: string;
}

export function ErrorNotifier() {
  const [errors, setErrors] = useState<ErrorItem[]>([]);
  const messages = useRef<HTMLDivElement>(null);

  const copyMessages = () => {
    if (messages.current) {
      const text = messages.current.innerText;
      navigator.clipboard.writeText(text);
    }
  };

  useEffect(() => {
    const abortController = new AbortController();

    const handler = (err: { code: number; message: string }) => {
      if (localStorage.ErrorNotifierEnabled !== 'true') {
        return;
      }

      if (err.code !== 0) {
        setErrors((prev) => [
          ...prev,
          {
            time: new Date().toLocaleString(),
            code: err.code,
            message: err.message,
          },
        ]);
      }
    };

    userEvents.on(CMEVENTS.CMD_FAILED, handler, abortController.signal);
    return () => {
      abortController.abort();
    };
  }, []);

  return (
    <div className='fixed right-4 bg-white text-[#f44336] bottom-4 w-[500px] z-[9999]'>
      {errors.length > 0 && (
        <>
          <h2>Command Error Messages (for Dev and Test Only)</h2>

          <div ref={messages}>
            {errors.map((err, idx) => (
              <div
                key={idx}
                className='mb-2 p-2 rounded'
              >
                <div>
                  <strong>Time:</strong> {err.time}
                </div>
                <div>
                  <strong>Code:</strong> {err.code}
                </div>
                <div>
                  <strong>Message:</strong> {err.message}
                </div>
              </div>
            ))}
          </div>

          <button
            className='mx-4'
            onClick={copyMessages}
          >
            Copy Messages
          </button>
          <button
            className='mx-4'
            onClick={() => setErrors([])}
          >
            Close
          </button>
        </>
      )}
    </div>
  );
}
